package com.ruoyi.common.utils;

import com.baidu.aip.face.AipFace;
import com.baidu.aip.ocr.AipOcr;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @Author: wwy
 * @Date: 2021/3/3 9:18
 */
public class AipBaiDuUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(AipBaiDuUtils.class);
    private static String APP_ID;
    private static String API_KEY;
    private static String SECRET_KEY;

    private static AipOcr aipOcrClient = null;
    private static AipFace aipFaceClient = null;

    static {
        Properties properties = new Properties();
        // 使用ClassLoader加载properties配置文件生成对应的输入流
        InputStream in = AipBaiDuUtils.class.getClassLoader().getResourceAsStream("baiduAipOcr.properties");
        // 使用properties对象加载输入流
        try {
            properties.load(in);
            APP_ID = String.valueOf(properties.get("APP_ID"));
            API_KEY = String.valueOf(properties.get("API_KEY"));
            SECRET_KEY = String.valueOf(properties.get("SECRET_KEY"));
            LOGGER.info("baiduAipOcr初始化成功,APP_ID:{},API_KEY:{},SECRET_KEY{}",APP_ID,API_KEY,SECRET_KEY);
        } catch (IOException e) {
            LOGGER.info("baiduAipOcr初始化失败");
        }
    }

    /**
     * 单列模式获取AipOcrClient
     * @return
     */
    public static AipOcr getAipOcrClient(){
        if(aipOcrClient == null){
            //重新加载
            //读取配置文件
            // 初始化一个AipOcr
            AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

            // 可选：设置网络连接参数
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
            AipBaiDuUtils.aipOcrClient = client;
        }
        return aipOcrClient;
    }

    public static AipFace getAipFaceClient(){
        if(aipFaceClient == null){
            // 初始化一个AipFace
            AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

            // 可选：设置网络连接参数
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
            AipBaiDuUtils.aipFaceClient = client;
        }
        return aipFaceClient;
    }

}
